#!/bin/bash

# 检查参数是否存在
if [ $# -ne 1 ]; then
    echo "Usage: $0 <debian_version>"
    echo "Available versions   : bullseye, bookworm"
    exit 1
fi

# 获取参数
DEBIAN_VERSION=$1

# 定义合法的 Ubuntu 版本数组
VALID_VERSIONS=("bullseye" "bookworm")

# 检查参数是否在合法版本中
if [[ ! " ${VALID_VERSIONS[@]} " =~ " ${DEBIAN_VERSION} " ]]; then
    echo "Error: Invalid Ubuntu version specified"
    echo "Available versions: ${VALID_VERSIONS[*]}"
    exit 1
fi

# 动态生成 Dockerfile 路径和镜像标签
DOCKERFILE="./Dockerfile.debian"
IMAGE_TAG="linux-dev-debian:${DEBIAN_VERSION}"
# echo "[debug]: DOCKERFILE: ${DOCKERFILE}" 
# echo "[debug]: IMAGE_TAG: ${IMAGE_TAG}" 

# 检查 Dockerfile 是否存在
if [ ! -f "$DOCKERFILE" ]; then
    echo "Error: Dockerfile not found at $DOCKERFILE"
    exit 1
fi

cd attachments
cp -a tsinghua.sources.${DEBIAN_VERSION}.list tsinghua.sources.list.tmp
cp -a ustc.sources.${DEBIAN_VERSION}.list ustc.sources.list.tmp
cd -

export DOCKER_BUILDKIT=1  # 启用 BuildKit

# 执行构建命令
echo "Building image with Ubuntu $DEBIAN_VERSION and type $IMAGE_TYPE..."
# echo "[debug]: docker build --progress=plain --build-arg DEBIAN_VERSION=\"${DEBIAN_VERSION}\" -t \"${IMAGE_TAG}\" -f \"${DOCKERFILE}\" ." 
docker build --progress=plain --build-arg DEBIAN_VERSION="$DEBIAN_VERSION" --build-arg UID=`id -u` -t "$IMAGE_TAG" -f "$DOCKERFILE" .

rm attachments/tsinghua.sources.list.tmp
rm attachments/ustc.sources.list.tmp
